﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace Practice
{
    /// <summary>
    /// PicUpHandler 的摘要说明
    /// </summary>
    public class PicUpHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            //context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");

            //context.Response.ContentType = "text/plain";
            context.Response.Charset = "utf-8";

            System.Drawing.Bitmap bitmap = null;   //按截图区域生成Bitmap
            System.Drawing.Image thumbImg = null;  //被截图（原图）； 
            System.Drawing.Graphics gps = null;    //存绘图对象   
            System.Drawing.Image finalImg = null;  //最终图片

            try
            {
                string pointX = context.Request.Params["x"]; //X坐标
                string pointY = context.Request.Params["y"]; //Y坐标
                string rlSize = context.Request.Params["width"]; //截图矩形的大小
                //byte[] blobURL = Encoding.UTF8.GetBytes(context.Request.Params["blobURL"]); //被截图图片地址
                string dataURL = context.Request.Params["dataURL"];
                string fileInfo = StringCutCharBefore(dataURL, ';'); //图片编码信息；
                string fileExtend = StringCutCharAfter(fileInfo, '/'); //图片后缀；
                byte[] data = Encoding.UTF8.GetBytes(StringCutCharAfter(context.Request.Params["dataURL"], ',')); //纯图片数据；
                

                if (!string.IsNullOrEmpty(pointX) && !string.IsNullOrEmpty(pointY) && data.Length > 0)
                {
                    bitmap = new System.Drawing.Bitmap(StrToInt(rlSize), StrToInt(rlSize)); //画布；
                   
                    string tempFilePath = SaveImageDataUrlToFileAndReturnFilePath(dataURL);                   
                    thumbImg = Image.FromFile(tempFilePath); //原图；

                    Rectangle rl = new Rectangle(StrToInt(pointX), StrToInt(pointY), StrToInt(rlSize), StrToInt(rlSize));   //得到截图矩形                 
                    gps = System.Drawing.Graphics.FromImage(bitmap); //读取绘图对象；
                    gps.DrawImage(thumbImg, 0, 0, rl, GraphicsUnit.Pixel); //将原图的指定区域绘制出来；
                    finalImg = bitmap;

                    if (!Directory.Exists(HttpContext.Current.Server.MapPath("/upload/user")))
                    {
                        Directory.CreateDirectory(HttpContext.Current.Server.MapPath("/upload/user"));
                    }
                    string finalPath = String.Format("/upload/user/final_{0}.{1}", DateTime.Now.ToString("yyyyMMddHHmmssffff"), fileExtend);

                    finalImg.Save(HttpContext.Current.Server.MapPath(finalPath));

                    bitmap.Dispose();
                    thumbImg.Dispose();
                    gps.Dispose();
                    finalImg.Dispose();
                    GC.Collect();

                    try
                    {
                        File.Delete(tempFilePath); //删除临时图片；
                    }
                    catch (Exception ex)
                    {
                        Console.Write(ex.ToString());
                    }

                    Newtonsoft.Json.Linq.JObject json = new JObject(new JProperty("result", "ok"), new JProperty("file", finalPath));                    
                    context.Response.Write(json);
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex.ToString());
                throw ex;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public int StrToInt(string str)
        {
            double numD = Convert.ToDouble(str);
            return Convert.ToInt32(numD);
        }

        /// <summary>
        /// 将前端传来的dataurl转成图片并返回文件地址
        /// http://bbs.csdn.net/topics/392016054#post-401562346
        /// </summary>
        /// <param name="dataUrl"></param>
        /// <returns></returns>
        public string SaveImageDataUrlToFileAndReturnFilePath(string dataUrl)
        {
            string fileinfo = StringCutCharBefore(dataUrl, ';'); //图片编码信息；
            string fileExtend = StringCutCharAfter(fileinfo, '/'); //图片后缀；
            if (!Directory.Exists(HttpContext.Current.Server.MapPath("/upload/image")))
            {
                Directory.CreateDirectory(HttpContext.Current.Server.MapPath("/upload/image"));
            }
            //if (fileExtend == "jpeg") { fileExtend = "jpg"; }

            string filename = HttpContext.Current.Server.MapPath(String.Format("/upload/image/{0}.{1}", Guid.NewGuid().ToString(), fileExtend));

            byte[] arrb = Convert.FromBase64String(StringCutCharAfter(dataUrl, ','));
            MemoryStream stream = new MemoryStream(arrb);
            StreamToFile(stream, filename);

            return filename;
        }
        public string StringCutCharBefore(string str, char c)
        {
            var index = str.IndexOf(c);
            return str.Substring(0, index);
        }
        public string StringCutCharAfter(string str, char c)
        {
            return str.Substring(str.IndexOf(c) + 1);
        }
        public void StreamToFile(Stream stream, string fileName)
        {
            // 把 Stream 转换成 byte[] 
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);

            // 设置当前流的位置为流的开始 
            stream.Seek(0, SeekOrigin.Begin);

            // 把 byte[] 写入文件 
            FileStream fs = new FileStream(fileName, FileMode.Create);
            BinaryWriter bw = new BinaryWriter(fs);
            bw.Write(bytes);
            bw.Close();
            fs.Close();
        }

    }
}